/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 获取全部驿站下拉框
 *  */
import React, { useCallback, forwardRef, useEffect, useState, useMemo } from 'react';
import { Select, Spin } from 'antd';
import { connect } from 'dva';
import { usePrevious } from 'ahooks';
import { isEqual } from 'lodash';

const { Option } = Select;

const Yzs = forwardRef((props, ref) => {
  const {
    loading,
    yzList = [],
    dispatch,
    value,
    onSelect,
    reqPayload = {}, //  接口请求参数
    repeatRequest = false, // 每次下拉是否重新请求数据
    showAll = true, // 展示全部
    requestType,
    ...restProps
  } = props;

  const prevReqPayload = usePrevious(reqPayload);

  const initList = useMemo(
    () =>
      (showAll
        ? [
            {
              id: 'all',
              cm_id: 'all',
              company_name: '全部驿站',
            },
          ]
        : []),
    [showAll],
  );

  const [list, setList] = useState(initList);

  const filterOption = useCallback(
    (input, option) =>
      option.props.children &&
      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
    [],
  );

  useEffect(() => {
    setList(prevList => [...prevList, ...yzList]);
  }, []);

  const onDropdownVisibleChange = useCallback(
    visible => {
      if (visible) {
        if (!repeatRequest && list.length > 1 && isEqual(reqPayload, prevReqPayload)) return;
        dispatch({
          type: requestType || 'global/getYzList',
          payload: {
            ...reqPayload,
          },
        }).then(res => {
          setList([...initList, ...res]);
        });
      }
    },
    [dispatch, reqPayload, repeatRequest, list, initList, requestType],
  );

  const handleSelect = useCallback(
    (val, options) => {
      onSelect && onSelect(val, options);
    },
    [onSelect],
  );

  return (
    <Select
      onDropdownVisibleChange={onDropdownVisibleChange}
      ref={ref}
      style={{ width: 250 }}
      placeholder="全部驿站"
      showSearch
      filterOption={filterOption}
      value={showAll ? value || 'all' : value}
      onSelect={handleSelect}
      {...restProps}
    >
      {loading ? (
        <Option disabled value="loading">
          <Spin />
        </Option>
      ) : (
        list.map(({ id, cm_id, company_name }) => (
          <Option key={id} value={cm_id} name={company_name}>
            {company_name}
          </Option>
        ))
      )}
    </Select>
  );
});

export default connect(
  ({ loading, global }) => ({
    yzList: global.yzList,
    loading: loading.effects['global/getYzList'],
  }),
  null,
  null,
  { forwardRef: true },
)(React.memo(Yzs));
